package com.weed.logging.impl;

/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import com.weed.core.WeedException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import com.weed.logging.Log;

import com.weed.logging.LogFactory;

public class LogFactoryImpl extends LogFactory { 

    public static final String LOG_PROPERTY ="com.weed.logging.Log";
    protected static final String LOG_PROPERTY_OLD ="com.weed.logging.log";
    private static final String LOG_INTERFACE ="com.weed.logging.Log";
    protected Hashtable attributes = new Hashtable();
    protected Hashtable instances = new Hashtable();
    private String logClassName;
    protected Constructor logConstructor = null;
    protected Class logConstructorSignature[] = {java.lang.String.class};
    protected Method logMethod = null;
    protected Class logMethodSignature[] = {LogFactory.class};

    public LogFactoryImpl() {
        super();
    }

    public Object getAttribute(String name) {
        return (attributes.get(name));
    }

    public String[] getAttributeNames() {
        Vector names = new Vector();
        Enumeration keys = attributes.keys();
        while (keys.hasMoreElements()) {
            names.addElement((String) keys.nextElement());
        }
        String results[] = new String[names.size()];
        for (int i = 0; i < results.length; i++) {
            results[i] = (String) names.elementAt(i);
        }
        return (results);
    }

    public Log getInstance(Class clazz) throws WeedException {
        return (getInstance(clazz.getName()));
    }

    public Log getInstance(String name) throws WeedException {
        Log instance = (Log) instances.get(name);
        if (instance == null) {
            instance = newInstance(name);
            instances.put(name, instance);
        }
        return (instance);

    }

    public void release() {

        instances.clear();
    }

    public void removeAttribute(String name) {

        attributes.remove(name);

    }

    public void setAttribute(String name, Object value) {

        if (value == null) {
            attributes.remove(name);
        } else {
            attributes.put(name, value);
        }

    }
    /**
     * 获得日志类。
     * @return
     */
    protected String getLogClassName() {
        // Return the previously identified class name (if any)
        if (logClassName != null) {
            return logClassName;
        }
        logClassName = (String) getAttribute(LOG_PROPERTY);
        if (logClassName == null) { // @deprecated
            logClassName = (String) getAttribute(LOG_PROPERTY_OLD);
        }
        if (logClassName == null) {
            try {
                logClassName = System.getProperty(LOG_PROPERTY);
            } catch (SecurityException e) {
                ;
            }
        }
        if (logClassName == null) { // @deprecated
            try {
                logClassName = System.getProperty(LOG_PROPERTY_OLD);
            } catch (SecurityException e) {
                ;
            }
        }
        if ((logClassName == null) && isLog4JAvailable()) {
            logClassName = "com.weed.logging.impl.Log4JLogger";
        }
        if (logClassName == null) {
            logClassName = "com.weed.logging.impl.SimpleLog";
        }
        return (logClassName);
    }

    protected Constructor getLogConstructor()
            throws WeedException {

        if (logConstructor != null) {
            return logConstructor;
        }
       String logClassName = getLogClassName();
        // Attempt to load the Log implementation class
        Class logClass = null;
        Class logInterface = null;
        try {
            logInterface = this.getClass().getClassLoader().loadClass(LOG_INTERFACE);
            logClass = loadClass(logClassName);
            if (logClass == null) {
                throw new WeedException("No suitable Log implementation for " + logClassName);
            }
            if (!logInterface.isAssignableFrom(logClass)) {
                Class interfaces[] = logClass.getInterfaces();
                for (int i = 0; i < interfaces.length; i++) {
                    if (LOG_INTERFACE.equals(interfaces[i].getName())) {
                        throw new WeedException("Invalid class loader hierarchy.  " +
                                "You have more than one version of '" +
                                LOG_INTERFACE + "' visible, which is " +
                                "not allowed.");
                    }
                }
                throw new WeedException("Class " + logClassName + " does not implement '" +
                        LOG_INTERFACE + "'.");
            }
        } catch (Throwable t) {
            throw new WeedException(t);
        }

        try {
            logMethod = logClass.getMethod("setLogFactory",
                    logMethodSignature);
        } catch (Throwable t) {
            logMethod = null;
        }

        // Identify the corresponding constructor to be used
        try {
            logConstructor = logClass.getConstructor(logConstructorSignature);
            return (logConstructor);
        } catch (Throwable t) {
            throw new WeedException("No suitable Log constructor " +
                    logConstructorSignature + " for " + logClassName, t);
        }
    }

    private static Class loadClass(final String name)
            throws ClassNotFoundException {
          Object result = AccessController.doPrivileged(
                new PrivilegedAction() {
                    public Object run() {
                        ClassLoader threadCL = getContextClassLoader();
                        if (threadCL != null) {
                            try {
                                return threadCL.loadClass(name);
                            } catch (ClassNotFoundException ex) {
                                // ignore
                            }
                        }
                        try {
                            return Class.forName(name);
                        } catch (ClassNotFoundException e) {
                            return e;
                        }
                    }
                });

        if (result instanceof Class) {
            return (Class) result;
        }

        throw (ClassNotFoundException) result;
    }

     protected boolean isLog4JAvailable() {
        try {
            loadClass("org.apache.log4j.Logger");
            loadClass("com.weed.logging.impl.Log4JLogger");
            return (true);
        } catch (Throwable t) {
            return (false);
        }
    }
    /**
     * 根据类名，初始化Log处理对象。
     * @param name 对象完整名称。
     * @return 日志处理对象。
     * @throws WeedException
     */
    protected Log newInstance(String name) throws WeedException {
         Log instance = null;
        try {
            Object params[] = new Object[1];
            params[0] = name;
            instance = (Log) getLogConstructor().newInstance(params);
            if (logMethod != null) {
                params[0] = this;
                logMethod.invoke(instance, params);
            }
            return (instance);
        } catch (InvocationTargetException e) {
            Throwable c = e.getTargetException();
            if (c != null) {
                throw new WeedException(c);
            } else {
                throw new WeedException(e);
            }
        } catch (Throwable t) {
            throw new WeedException(t);
        }

    }
}
